#include "mainwindow.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QFileDialog>
#include <QInputDialog>
#include "trendwindow.h"
#include <QtWidgets>
#include <QTableWidget>
#include <QHeaderView>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QFile>
#include <QTextStream>
#include <QHeaderView>
#include <QInputDialog>
#include <QtCharts/QChartView>
#include <QtCharts/QLineSeries>
#include "aichatdialog.h"
#include "trendwindow.h"
#include "trendwindow.h"


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    // 初始化输入框和按钮
    weightInput = new QLineEdit(this);
    weightInput->setPlaceholderText("体重 (kg)");

    heightInput = new QLineEdit(this);
    heightInput->setPlaceholderText("身高 (cm)");

    genderInput = new QComboBox(this);
    genderInput->addItem("男");
    genderInput->addItem("女");

    ageGroupInput = new QComboBox(this);
    ageGroupInput->addItem("18岁以下");
    ageGroupInput->addItem("18-35岁");
    ageGroupInput->addItem("36-55岁");
    ageGroupInput->addItem("55岁以上");

    dateInput = new QDateEdit(QDate::currentDate(), this);
    dateInput->setCalendarPopup(true);

    calculateButton = new QPushButton("计算BMI", this);
    connect(calculateButton, &QPushButton::clicked, this, &MainWindow::calculateBMI);

    reportButton = new QPushButton("生成报告", this);
    connect(reportButton, &QPushButton::clicked, this, &MainWindow::generateReport);

    predictButton = new QPushButton("预测趋势", this);
    connect(predictButton, &QPushButton::clicked, this, &MainWindow::predictTrend);

    goalButton = new QPushButton("设定目标", this);
    connect(goalButton, &QPushButton::clicked, this, &MainWindow::setGoal);

    historyButton = new QPushButton("查看历史", this);
    connect(historyButton, &QPushButton::clicked, this, &MainWindow::loadHistory);

    exportButton = new QPushButton("导出数据", this);
    connect(exportButton, &QPushButton::clicked, this, &MainWindow::exportHistory);

    aiChatButton = new QPushButton("BMI智能问答", this);
    connect(aiChatButton, &QPushButton::clicked, this, &MainWindow::openAIChat);

    bmiResult = new QLabel("BMI: ", this);
    bmiCategory = new QLabel("健康区间: ", this);

    bmiProgress = new QProgressBar(this);
    bmiProgress->setRange(0, 100);
    bmiProgress->setTextVisible(false);

    reportOutput = new QTextEdit(this);
    reportOutput->setReadOnly(true);

    historyTable = new QTableWidget(this);
    historyTable->setColumnCount(3);
    historyTable->setHorizontalHeaderLabels({"日期", "BMI值", "健康区间"});
    historyTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    // 布局
    QVBoxLayout *layout = new QVBoxLayout();
    layout->addWidget(weightInput);
    layout->addWidget(heightInput);
    layout->addWidget(genderInput);
    layout->addWidget(ageGroupInput);
    layout->addWidget(dateInput);
    layout->addWidget(calculateButton);
    layout->addWidget(reportButton);
    layout->addWidget(predictButton);
    layout->addWidget(goalButton);
    layout->addWidget(historyButton);
    layout->addWidget(exportButton);
    layout->addWidget(aiChatButton);
    layout->addWidget(bmiResult);
    layout->addWidget(bmiCategory);
    layout->addWidget(bmiProgress);
    layout->addWidget(reportOutput);
    layout->addWidget(historyTable);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);
}

void MainWindow::calculateBMI()
{
    bool ok;
    double weight = weightInput->text().toDouble(&ok);
    if (!ok || weight <= 0) {
        QMessageBox::warning(this, "错误", "请输入有效的体重");
        return;
    }

    double height = heightInput->text().toDouble(&ok);
    if (!ok || height <= 0) {
        QMessageBox::warning(this, "错误", "请输入有效的身高");
        return;
    }

    height /= 100; // 转换为米
    double bmi = weight / (height * height);
    bmiResult->setText(QString("BMI: %1").arg(bmi, 0, 'f', 2));

    // 设置健康区间和进度条颜色
    QString category;
    if (bmi < 18.5) {
        category = "偏瘦";
        bmiProgress->setStyleSheet("QProgressBar::chunk { background-color: blue; }");
    } else if (bmi < 24) {
        category = "正常";
        bmiProgress->setStyleSheet("QProgressBar::chunk { background-color: green; }");
    } else if (bmi < 28) {
        category = "超重";
        bmiProgress->setStyleSheet("QProgressBar::chunk { background-color: yellow; }");
    } else {
        category = "肥胖";
        bmiProgress->setStyleSheet("QProgressBar::chunk { background-color: red; }");
    }
    bmiCategory->setText(QString("健康区间: %1").arg(category));

    // 设置进度条值
    bmiProgress->setValue((bmi / 40) * 100); // 假设BMI最大值为40

    // 保存数据
    saveToHistory(dateInput->date(), bmi, category);
}

void MainWindow::generateReport()
{
    if (bmiResult->text() == "BMI: ") {
        QMessageBox::warning(this, "错误", "请先计算BMI");
        return;
    }

    double bmi = bmiResult->text().split(": ")[1].toDouble();
    QString gender = genderInput->currentText();
    QString ageGroup = ageGroupInput->currentText();

    QString advice = getHealthAdvice(bmi, gender, ageGroup);
    
    AdviceWindow *adviceWindow = new AdviceWindow(this);
    adviceWindow->setAdviceText(advice);
    adviceWindow->show();
}

void MainWindow::predictTrend()
{
    QFile file("bmi_history.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "没有历史数据可供预测");
        return;
    }

    QVector<double> bmiHistory;
    QVector<QDate> dates;
    QTextStream stream(&file);
    while (!stream.atEnd()) {
        QString line = stream.readLine();
        QStringList parts = line.split(",");
        if (parts.size() == 3) {
            dates.append(QDate::fromString(parts[0], "yyyy-MM-dd"));
            bmiHistory.append(parts[1].toDouble());
        }
    }
    file.close();

    if (bmiHistory.size() < 3) {
        QMessageBox::warning(this, "错误", "至少需要3次测量数据才能预测趋势");
        return;
    }

    // 简单线性预测
    double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
    for (int i = 0; i < bmiHistory.size(); ++i) {
        sumX += i;
        sumY += bmiHistory[i];
        sumXY += i * bmiHistory[i];
        sumX2 += i * i;
    }

    double n = bmiHistory.size();
    double slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
    double intercept = (sumY - slope * sumX) / n;

    // 预测未来6个月
    QString prediction = "未来6个月BMI预测:\n";
    for (int i = 0; i < 6; ++i) {
        double predictedBmi = slope * (n + i) + intercept;
        QDate date = QDate::currentDate().addMonths(i + 1);
        prediction += date.toString("yyyy-MM-dd") + ": " + QString::number(predictedBmi, 'f', 2) + "\n";
    }

    reportOutput->setText(prediction);
}

void MainWindow::setGoal()
{
    bool ok;
    double targetBmi = QInputDialog::getDouble(this, "设定目标", "请输入目标BMI值:", 22, 10, 40, 1, &ok);
    if (!ok) return;

    double currentBmi = bmiResult->text().split(": ")[1].toDouble();
    double monthsNeeded = qAbs(targetBmi - currentBmi) / 0.5; // 假设每月变化0.5

    QString plan = QString("当前BMI: %1\n目标BMI: %2\n预计需要%3个月达到目标。\n建议:").arg(currentBmi).arg(targetBmi).arg(monthsNeeded);
    if (targetBmi < currentBmi) {
        plan += "\n- 每周至少3次有氧运动\n- 减少高热量食物摄入\n- 定期监测体重";
    } else {
        plan += "\n- 增加蛋白质摄入\n- 每周进行力量训练\n- 保持均衡饮食";
    }

    reportOutput->setText(plan);
}

void MainWindow::loadHistory()
{
    // 历史记录功能已整合到ResultWindow中
    QMessageBox::information(this, "提示", "历史记录功能已整合到结果窗口中");
}

void MainWindow::exportHistory()
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出数据", "", "CSV文件 (*.csv)");
    if (fileName.isEmpty()) return;

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法保存文件");
        return;
    }

    QTextStream stream(&file);
    stream << "日期,BMI值,健康区间\n";

    QFile historyFile("bmi_history.txt");
    if (historyFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream historyStream(&historyFile);
        while (!historyStream.atEnd()) {
            stream << historyStream.readLine() << "\n";
        }
        historyFile.close();
    }

    file.close();
    QMessageBox::information(this, "成功", "数据已导出到" + fileName);
}

QString MainWindow::getHealthAdvice(double bmi, const QString &gender, const QString &ageGroup)
{
    QString advice;
    if (bmi < 18.5) {
        advice = "您的BMI值偏低，可能存在营养不良的风险。\n";
        if (gender == "男") {
            advice += "男性建议增加蛋白质摄入，适当进行力量训练。\n";
        } else {
            advice += "女性建议均衡饮食，避免过度节食。\n";
        }
    } else if (bmi < 24) {
        advice = "您的BMI值在正常范围内，继续保持健康的生活方式。\n";
    } else if (bmi < 28) {
        advice = "您的BMI值偏高，可能存在超重风险。\n";
        if (ageGroup == "18-35岁") {
            advice += "年轻人建议增加有氧运动，控制饮食。\n";
        } else {
            advice += "中老年人建议适度运动，避免高热量食物。\n";
        }
    } else {
        advice = "您的BMI值过高，存在肥胖风险。\n";
        advice += "建议咨询医生或营养师，制定科学的减重计划。\n";
    }

    advice += "年龄组: " + ageGroup + "\n";
    advice += "性别: " + gender + "\n";
    return advice;
}

void MainWindow::saveToHistory(const QDate &date, double bmi, const QString &category)
{
    QFile file("bmi_history.txt");
    if (file.open(QIODevice::Append | QIODevice::Text)) {
        QTextStream stream(&file);
        stream << date.toString("yyyy-MM-dd") << "," << bmi << "," << category << "\n";
        file.close();
    }
}

void MainWindow::openAIChat()
{
    AIChatDialog *chatDialog = new AIChatDialog(this);
    chatDialog->setAttribute(Qt::WA_DeleteOnClose);
    chatDialog->exec();
}

MainWindow::~MainWindow()
{
    // 清理资源
}
